﻿using System;
using System.IO;
using System.Data;
using System.Windows;
using System.Collections;
using System.Windows.Input;
using System.ComponentModel;
using System.Windows.Controls;
using Sinacor.Infra.UI.Common;
using Sinacor.Infra.UI.Controls;
using Sinacor.Infra.UI.Controls.SmartClient;
using System.Collections.Generic;
using Sinacor.Infra.UI.Controls.SmartClient.Validation;
using Sinacor.UI.Bovespa.Movimento.Presenter;
using Sinacor.Infra.UI.Authorization;

namespace Sinacor.UI.Bovespa.Movimento.View.SmartClient
{
    public partial class AcertoIRRF : SinacorWindow, IAcertoIRRF
    {
        #region Atributos
        Presenter.AcertoIRRF _presenter;
        #endregion

        #region Construtor

        public AcertoIRRF()
        {
            InitializeComponent();            
            _presenter = new Sinacor.UI.Bovespa.Movimento.Presenter.AcertoIRRF(this);
            this.DataContext = _presenter;
            DtgAcertos.NewItemType = typeof(Model.AcertoIRRF);          
            this.AfterInitialize += new RoutedEventHandler(AcertoIRRF_AfterInitialize);          
        }

        void AcertoIRRF_AfterInitialize(object sender, RoutedEventArgs e)
        {
            this.ShowUserWaitingProcess();
            _presenter.Inicializar();
            this.CboTipoImpostoFiltro.ItemsSource = EnumWrapper<Model.Enum.TipoImposto>.GetEnums();
            _presenter.FiltroAcertoIRRF.Periodo = new Sinacor.UI.Bovespa.Movimento.Model.Periodo();
            DtgAcertos.AllowBeginInsert = false;
            DtgAcertos.AllowBeginUpdate = false;
            DtgAcertos.AllowSave = false;               
            this.HideUserWaitingProcess();
        }    
        #endregion

        #region IAcertoIRRF Members

        public void AtualizarComboBolsa()
        {
            SinacorComboBox cmb = null;

            if (DtgAcertos.IsInserting)
            {                
               cmb = (SinacorComboBox)ControlHelper.FindChild(this.DtgAcertos.GetInsertionRow(), "CboBolsaGrid");

                if (cmb != null)
                {
                    cmb.ItemsSource = _presenter.ListaBolsas;
                    cmb.UpdateTarget(SinacorComboBox.ItemsSourceProperty);
                }    
            }
            else if (DtgAcertos.IsUpdating)
            {                
               cmb = (SinacorComboBox)ControlHelper.FindChild(this.DtgAcertos.GetRow(this.DtgAcertos.EditIndex), "CboBolsaGrid");

                if (cmb != null)
                {
                    cmb.ItemsSource = _presenter.ListaBolsas;
                    cmb.UpdateTarget(SinacorComboBox.ItemsSourceProperty);
                }
            }            
        }

        public void AtualizarComboDiasLiquidacao()
        {
            SinacorComboBox cmb = null;

            if (DtgAcertos.IsInserting)
            {
                cmb = (SinacorComboBox)ControlHelper.FindChild(this.DtgAcertos.GetInsertionRow(), "CboDiasLiqGrid");

                if (cmb != null)
                {
                    cmb.ItemsSource = _presenter.ListaDiasLiquidacaoAcerto;
                    cmb.UpdateTarget(SinacorComboBox.ItemsSourceProperty);
                }
            }
            else if (DtgAcertos.IsUpdating)
            {
                cmb = (SinacorComboBox)ControlHelper.FindChild(this.DtgAcertos.GetRow(this.DtgAcertos.EditIndex), "CboDiasLiqGrid");

                if (cmb != null)
                {
                    cmb.ItemsSource = _presenter.ListaDiasLiquidacaoAcerto;
                    cmb.UpdateTarget(SinacorComboBox.ItemsSourceProperty);
                }

                Model.AcertoIRRF acerto = ((Model.AcertoIRRF)DtgAcertos.EditItem);

                if (acerto != null)
                {
                    if (acerto.Origem == "DIG")
                        cmb.IsEnabled = true;
                    else
                    {                        
                        cmb.IsEnabled = false;
                    }
                }    
            }                   
        }

        public void AtualizarGridAcertosIRRF()
        {
            DtgAcertos.UpdateTarget(SinacorDataGrid.ItemsSourceProperty);
        }

        public void InformarAlteracaoAcertoSucesso()
        {
            SinacorMessageBox.Show(this.FindResource("FaturamentoBovespa.Movimento.Message.AlteracaoRealizada").ToString(),
                                  SinacorMessageBoxButton.Ok,
                                  SinacorMessageBoxImage.Information);
        }

        public void InformarInclusaoAcertoSucesso()
        {
            SinacorMessageBox.Show(this.FindResource("FaturamentoBovespa.Movimento.Message.AcertoIncluido").ToString(),
                                  SinacorMessageBoxButton.Ok,
                                  SinacorMessageBoxImage.Information);
        }

        public void InformarNenhumRegistroEncontrado()
        {
            ShowError("FaturamentoBovespa.Movimento.Message.DadosNaoEncontrados");
        }

        #endregion

        #region Eventos
        private void BtnPesquisar_OnBufferedClick(object sender, RoutedEventArgs e, int clickCount)
        {
            this.ClearServiceErrors();

            this.ShowUserWaitingProcess();

            _presenter.ListaAcertosIRRF = new ModelCollection<Sinacor.UI.Bovespa.Movimento.Model.AcertoIRRF>();
            this.AtualizarGridAcertosIRRF();

            _presenter.FiltroAcertoIRRF.TipoImposto = (Model.Enum.TipoImposto?)CboTipoImpostoFiltro.SelectedValue;

            _presenter.ConsularAcertosIRRF();

            if (DtgAcertos.Items.Count > 0)
            {
                DtgAcertos.AllowBeginInsert = true;
                DtgAcertos.AllowBeginUpdate = true;
                DtgAcertos.AllowSave = true;    
            }
            else
            {
                DtgAcertos.AllowBeginInsert = false;
                DtgAcertos.AllowBeginUpdate = false;
                DtgAcertos.AllowSave = false;               
            }

            this.HideUserWaitingProcess();
        }

        private void BtnNovaPesquisa_OnBufferedClick(object sender, RoutedEventArgs e, int clickCount)
        {
            this.Limpar();
        }

        private void DtgAcertos_EndingInsert(object sender, CancelItemEventArgs e)
        {
            if (e.OriginalSource is BaseRow)
            {
                this.ClearServiceErrors();
                if (DtgAcertos.IsInserting)
                {
                    SinacorComboBox cbo = null;

                    Model.AcertoIRRF model = (Model.AcertoIRRF)e.ItemInfo.Item;
                    model.IndicadorLiminarIRDT = false;
                    model.CodigoRetencao = _presenter.ListaAcertosIRRF[0].CodigoRetencao;
                    model.TipoImposto = _presenter.ListaAcertosIRRF[0].TipoImposto;
                    model.DataFundacao = _presenter.ListaAcertosIRRF[0].DataFundacao;
                    model.CPFCNPJ = _presenter.ListaAcertosIRRF[0].CPFCNPJ;
                    model.CodigoDependencia = _presenter.ListaAcertosIRRF[0].CodigoDependencia;
                    model.Origem = _presenter.ListaAcertosIRRF[0].Origem;
                    

                    cbo = (SinacorComboBox)ControlHelper.FindChild(this.DtgAcertos.GetInsertionRow(), "CboDiasLiqGrid");
                    model.DiasLiquidacaoAcerto = (Model.DiasLiquidacaoAcerto)cbo.SelectedItem;

                    cbo = (SinacorComboBox)ControlHelper.FindChild(this.DtgAcertos.GetInsertionRow(), "CboBolsaGrid");
                    model.Bolsa = ((Model.Bolsa)cbo.SelectedItem).CodigoBolsa;
                    model.DescricaoBolsa = ((Model.Bolsa)cbo.SelectedItem).Descricao;
                    
                    this.ShowUserWaitingProcess();
                    if (!_presenter.IncluirAcertoIRRF(model))                    
                        e.Cancel = true;
                    this.HideUserWaitingProcess();
                }
                else if (DtgAcertos.IsUpdating)
                {
                    SinacorComboBox cbo = null;
                    Model.AcertoIRRF model = (Model.AcertoIRRF)e.ItemInfo.Item;
                    
                    cbo = (SinacorComboBox)ControlHelper.FindChild(this.DtgAcertos.GetRow(this.DtgAcertos.EditIndex), "CboDiasLiqGrid");
                    if (cbo.SelectedItem != null)
                        model.DiasLiquidacaoAcerto = (Model.DiasLiquidacaoAcerto)cbo.SelectedItem;                                        

                    this.ShowUserWaitingProcess();
                    if (!_presenter.AlterarAcertoIRRF(model))
                        e.Cancel = true;
                    this.HideUserWaitingProcess();
                }
                this.ClearChanges();
                ExpPesquisa.IsEnabled = true;    
            }
        }

        private void DtgAcertos_UpdateBegun(object sender, ItemEventArgs e)
        {
            if (e.OriginalSource is BaseRow)
            {
                this.AtualizarComboBolsa();
                this.AtualizarComboDiasLiquidacao();
                this.ConfigurarComboCNPJ();
                ExpPesquisa.IsEnabled = false;


                if (DtgAcertos.IsUpdating)
                {
                    SinacorComboBox cmb = (SinacorComboBox)ControlHelper.FindChild(this.DtgAcertos.GetRow(this.DtgAcertos.EditIndex), "CboDiasLiqGrid");

                    if (cmb != null)
                    {
                        Model.AcertoIRRF model = (Model.AcertoIRRF)e.ItemInfo.Item;
                        cmb.SelectedValue = model.DiasLiquidacaoAcerto.DiasLiquidacao;
                    }
                }
                
            }            
        }

        private void DtgAcertos_CancelingInsert(object sender, CancelItemEventArgs e)
        {
            if (e.OriginalSource is SinacorDataGrid)
            {
                ExpPesquisa.IsEnabled = true;
            }
        }
        #endregion

        #region Métodos

        private void Limpar()
        {
            this.ClearServiceErrors();
            _presenter.FiltroAcertoIRRF = new Sinacor.UI.Bovespa.Movimento.Model.Parameter.FiltroAcertoIRRF();
            _presenter.FiltroAcertoIRRF.Periodo = new Sinacor.UI.Bovespa.Movimento.Model.Periodo();   
            txtFornecedorFiltro.ComboSelection = null;
            txtClienteFiltro.UpdateTarget(SinacorInt32TextBox.ValueProperty);
            CboTipoImpostoFiltro.SelectedIndex = -1;
            DtpDe.UpdateTarget(SinacorDatePicker.ValueProperty);
            DtpAte.UpdateTarget(SinacorDatePicker.ValueProperty);
            _presenter.ListaAcertosIRRF = new ModelCollection<Sinacor.UI.Bovespa.Movimento.Model.AcertoIRRF>();
            this.AtualizarGridAcertosIRRF();

            DtgAcertos.AllowBeginInsert = false;
            DtgAcertos.AllowBeginUpdate = false;
            DtgAcertos.AllowSave = false;

            ExpPesquisa.IsEnabled = true;
        }

        private void ConfigurarComboCNPJ()
        {
            SinacorIdentificadorInvestidor txt = null;
            Model.AcertoIRRF model = (Model.AcertoIRRF)DtgAcertos.EditItem;

            if (DtgAcertos.IsUpdating)
            {
                txt = (SinacorIdentificadorInvestidor)ControlHelper.FindChild(this.DtgAcertos.GetRow(this.DtgAcertos.EditIndex), "txtCpfCnpjGrid");

                if (txt != null && model != null)
                {
                    if (model.CPFCNPJ.ToString().Length > 11)                   
                        txt.ComboSelection = SelectionComboType.CNPJ;                   
                    else
                        txt.ComboSelection = SelectionComboType.CPF;
                }
            }               
        }
        
        #endregion
        
    }
}

